package com.itbaizhan.controller;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload2.core.DiskFileItem;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.jakarta.JakartaServletDiskFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Controller
public class Upload {

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request) throws Exception {
        // 创建文件夹，存放上传文件
        // 1.设置上传文件夹路径
        String realPath = "D:/JavaCode/springmvclearn/upload";
        // 2.判断该目录是否存在，如果不存在，创建该目录
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }


        // 分析请求体，找到上传文件数据
        // 1.创建磁盘文件工厂
        DiskFileItemFactory factory = DiskFileItemFactory.builder().get();
        // 2.创建上传数据分析器对象
        JakartaServletDiskFileUpload upload = new JakartaServletDiskFileUpload(factory);
        // 3.利用分析器对象解析请求体，返回所有数据项
        List<DiskFileItem> fileItems = upload.parseRequest(request);
        // 4.遍历所有数据，找到文件项（非表单项）
        for (FileItem fileItem : fileItems) {
            if (!fileItem.isFormField()) {
                // 将文件数据写入文件夹
                // 1.获取文件名
                String name = fileItem.getName();
                // 2.将文件写入磁盘
                fileItem.write(Paths.get(realPath, name));
                // 3.删除内存中的临时文件
                fileItem.delete();
            }
        }
        return "baizhan";
    }

    /**
     * @param upload 名字必须和前端页面中input标签中的name属性一致，否则会导致参数封装失败
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload2")
    public String upload2(MultipartFile upload) throws IOException {
        String realPath = "D:/JavaCode/springmvclearn/upload";
        File dir = new File(realPath);

        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filename = upload.getOriginalFilename();
        filename = UUID.randomUUID() + filename;
        File file1 = new File(dir, filename);
        upload.transferTo(file1);
        return "baizhan";
    }


    @RequestMapping("/upload3")
    public String upload3(MultipartFile[] files) throws IOException {
        String realPath = "D:/JavaCode/springmvclearn/upload";
        File dir = new File(realPath);

        if (!dir.exists()) {
            dir.mkdirs();
        }

        for (MultipartFile file : files) {
            String name = file.getOriginalFilename();
            name = UUID.randomUUID() + name;
            File file1 = new File(dir, name);
            file.transferTo(file1);
        }
        return "baizhan";
    }

    @RequestMapping("/upload4")
    @ResponseBody
    public String upload4(MultipartFile file, HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/upload");
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String name = UUID.randomUUID() + file.getOriginalFilename();
        File file1 = new File(dir, name);
        file.transferTo(file1);
        System.out.println("文件保存路径：" + file1.getAbsolutePath());

        return "/upload/" + name;
    }

    @RequestMapping("/show")
    public String show(Model model) {
        String path = "D:/JavaCode/springmvclearn/upload";
        File file = new File(path);
        String[] files = file.list();

        model.addAttribute("files", files);
        return "download";
    }

    @RequestMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        String path = "D:/JavaCode/springmvclearn/upload";
        File file = new File(path, fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(FileUtils.readFileToByteArray(file));
        outputStream.flush();
        outputStream.close();
    }

}
